<?php
// 前台用户控制器
class Controller_WWW_User extends Controller
{
    public function __construct ($req, $res)
    {
        parent::__construct($req, $res);
    }

    public function action_login ()
    {
        $post = $this->request->post();
        $type  = 'WEB';         // 来自网站注册
        $email = Arr::get($post, 'email');
//        $code  = Arr::get($post, 'code');
        $utype  = Arr::get($post, 'utype');
        $password = Arr::get($post, 'password');
        $utype = strtoupper($utype);
//        $img = new Securimage();
//        $codeServer  = strtolower($img->getCode());

        $ret = array('status' => 0, 'errormsg' => NULL);
//        if($code != $codeServer){
//            $ret['errormsg'] = "验证码错误";
//            $ret['status']   = 1;
//        }else{
            $user = new User_V2_Guest;
            $data = $this->login_user($email,$password,$type);
            //账户不存在或者账户active=1
            if($data['status'] !== false){
                if ($user->login($email, $password, $type,$utype))
                {//账户status！=99且账户存在
                    $ret['status'] = 0;
                }
                else
                {//账户不存在或status=99
                    $ret['errormsg'] = "你输入的密码或是邮箱地址/手机号码错误，请重新输入";
                    $ret['status']   = 1;
                }
            //账户存在但是active ！=1
            }else{
                $ret['errormsg'] = "请先激活邮箱";
                $ret['status']   = 2;
                $ret['telActive'] = $data['telActive'];
                $ret['active'] = $data['active'];
            }

//        }
        echo json_encode($ret);
    }

    public function action_logout ()
    {
        $user = User::currentUser();
        $user->logout();

        Util_User::user_offline($user->getUserUid());
        $refer = $this->request->referrer();
        if (preg_match('/\/user\/logout/', $refer))
            $this->request->redirect('/');
        else
            $this->request->redirect('/');

    }

    public function action_tourist_reg(){
        $post = $this->request->post();
        $type  = 'WEB';
        $way = trim(Arr::get($post, 'way'));
        $utype = Arr::get($post, 'type');
        $password = Arr::get($post, 'password');

        if($way=='mail'){
        	$email = Arr::get($post, 'email');
        	$code  = strtolower(Arr::get($post, 'code'));
        	$img = new Securimage();
        	$codeServer  = strtolower($img->getCode());
            if($code != $codeServer){
               $ret['errormsg'] = "验证码错误";
               $ret['status']   = 1;
            }else{
               if($this->valid_email($email,'TOURIST')){
                  $ret['errormsg'] = "邮箱已被使用";
                  $ret['status']   = 2;
               }else{
                  $uid = User::createUser($type,$email,md5($password),'新用户','/resource/skin/img/index_mingxing.png',NULL,strtoupper($utype));
                  if ($uid > 0)
                  {
                    $mail_data = User_Subscribe::user_activation($uid,$email,'confirm');
                    $data['uid'] = $uid;
                    User_UserInfo::create($data);
                    $status = $mail_data['status'];
                    if(!$status){
                        $ret['status'] = 5;
                        $ret['errormsg'] = "注册发生错误，请重试";
                    }else {
                        $ret['url'] = $mail_data['url'];
                        $ret['status'] = 0;
                    }
                  }
                  else
                  {
                    $ret['errormsg'] = "注册发生错误，请重试";
                    $ret['status']   = 5;
                  }
                }
           }
        }

        else{
        	$sms_code = Arr::get($post, 'sms_code');
        	$areacode = ltrim(Arr::get($post, 'areacode'),'+');
        	$phone = Arr::get($post, 'num');
            $code  = strtolower(Arr::get($post, 'code'));
            $img = new Securimage();
        	$codeServer  = strtolower($img->getCode());
        	if($code != $codeServer){
        		$ret['errormsg'] = "验证码错误";
        		$ret['status']   = 1;
        	}else{	
        	list($status,$msg) = $this->get_message($sms_code,$areacode.$phone);
        	
        	if(!$status){
        		$ret['errormsg'] = $msg;
        		$ret['status']   = 3;
        		echo json_encode($ret);
        		exit;
        	}
        	if($this->valid_phone($phone,'TOURIST')){
        		$ret['errormsg'] = "该电话号码已被注册";
        		$ret['status']   = 4;
        	}else{
        		$uid = User::createUser($type,NULL,md5($password),'新用户','/resource/skin/img/index_mingxing.png',NULL,strtoupper($utype));
        		if ($uid > 0)
        		{	
        			$ret['status'] = 0;
        			//在用户信息补充表中建立一条记录
        			$data['uid'] = $uid;
                                $data['userPhone'] = "+".$areacode.trim($phone);
        			User_UserInfo::create($data);
        			//邮箱状态改为有效
        			$data_phone['active']=1;
        			$data_phone['telActive'] = 1;
        			$data_phone['telCode'] = $areacode;
        			$data_phone['telNum'] = $phone;
        			$data_phone['changed'] = time();
             		User_Account::update($data_phone, 'uid', $uid);
        			
        		}
        		else
        		{
        			$ret['errormsg'] = "注册发生错误，请重试";
        			$ret['status']   = 5;
        		}
        	}
           }
        }
        echo json_encode($ret);
        exit;
    }

    public function action_guider_reg(){
        $post = $this->request->post();
//        var_dump($post);
//        exit;
        $type  = 'WEB';
        $email = Arr::get($post, 'email');
        $sms_code = Arr::get($post, 'sms_code');
        $areacode = ltrim(Arr::get($post, 'areacode'),'+');
        $phone = Arr::get($post, 'num');
        $code  = strtolower(Arr::get($post, 'code'));
        $data['userFamily']  = Arr::get($post, 'xing');
        $data['userName']  = Arr::get($post, 'ming');
        $data['userGender']  = Arr::get($post, 'gender');
        $password = Arr::get($post, 'password');
        $utype = Arr::get($post, 'type');
        $img = new Securimage();
        $codeServer  = strtolower($img->getCode());
        $ret = array('status' => 0, 'errormsg' => NULL);

        if($code != $codeServer){
            $ret['errormsg'] = "验证码错误";
            $ret['status']   = 1;
        }else{
            list($status,$msg) = $this->get_message($sms_code,$areacode.$phone);

            if(!$status){
                $ret['errormsg'] = $msg;
                $ret['status']   = 3;
                echo json_encode($ret);
                exit;
            }

            if($this->valid_email($email,'GUIDER')){
                $ret['errormsg'] = "邮箱已被使用";
                $ret['status']   = 2;
            }
            elseif($this->valid_phone($phone,'GUIDER')){
                $ret['errormsg'] = "该电话号码已被注册";
                $ret['status']   = 4;
            }
            else{
                $uid = User::createUser($type,$email,md5($password),$data['userFamily'].$data['userName'],'/resource/skin/img/index_mingxing.png',$data['userGender'],strtoupper($utype));
                if ($uid > 0)
                {
                    $mail_data = User_Subscribe::user_activation($uid,$email,'confirm');
                    $data['uid'] = $uid;
                    $data['userPhone'] = "+".$areacode.trim($phone);
                    User_UserInfo::create($data);
                    $status = $mail_data['status'];
                    if(!$status){
                        $ret['status'] = 5;
                        $ret['errormsg'] = "注册发生错误，请重试";
                    }else{
                        $ret['url'] = $mail_data['url'];
                        $ret['status']   = 0;
                        $data_phone['telActive'] = 1;
                        $data_phone['telCode'] = $areacode;
                        $data_phone['telNum'] = $phone;
                        $data_phone['changed'] = time();
                        User_Account::update($data_phone, 'uid', $uid);
                    }
                }
                else
                {
                    $ret['errormsg'] = "注册发生错误，请重试";
                    $ret['status']   = 5;
                }
            }
        }
        echo json_encode($ret);
        exit;
    }

    //验证短信
    public function get_message($code,$num){
        $rs = DB::select()
            ->from('user_v2_mobile_code')
            ->where('code','=',$code)
            ->where('mobile','=',"+".$num)
            ->order_by('created','desc')
            ->execute();
        if($rs->count() > 0){
            $arr = $rs->current();
            $sub = time() - $arr['created'];
            if($sub > 1200){
                return array(false,'短信验证码时间超时');
            }
            return array(true,'短信验证通过');
        }
        return array(false,'短信验证码不正确');
    }

    //保存用户信息
    public function action_add_info(){
        $post = $this->request->post();
        $uid = Arr::get($post,'uid');
        $data = User_UserInfo::user_checkout('uid',$uid)->current();
        $msg = array('status'=>1,'msg'=>'抱歉，出错了，稍后再试');
        if(empty($data)){
            $row = User_UserInfo::create($post);
        }else{
            $save['userFamily'] = Arr::get($post,'userFamily');
            $save['userName'] = Arr::get($post,'userName');
            $save['userGender'] = Arr::get($post,'userGender');
            $save['userAge'] = Arr::get($post,'userAge');
            $save['userPhone'] = Arr::get($post,'code').Arr::get($post,'userPhone');
            $row = User_UserInfo::update($save,'uid',$uid);
        }
        if($row > 0){
            $msg['status'] = 0;
            $msg['msg'] = "";
        }
        echo json_encode($msg);
    }

    //验证邮箱是否存在
    public function valid_email($email,$type){
        $count = DB::select()
            ->from('user_v2')
            ->where('userId','=',$email)
//            ->where('utype','=',$type)
            ->execute()
            ->count();

        if($count > 0){
           return true;
        }
        return false;
    }
    //验证电话是否已存在
    public function valid_phone($phone,$type){
    	$count = DB::select()
    	->from('user_v2')
    	->where('telNum','=',$phone)
//        ->where('utype','=',$type)
    	->execute()
    	->count();
    
    	if($count > 0){
    		return true;
    	}
    	return false;
    }
    //登录验证
    public function login_user($mobile, $password, $type = 'WEB')
    {
        //
        $query = DB::select()
            ->from('user_v2')
            ->where_open()
            ->where('userId', '=', $mobile)
            ->or_where('telNum','=',$mobile)
            ->where_close()
//            ->where('userToken', '=', md5($password))
            ->where('source', '=', $type)
            ->execute();
        $data['status'] = true;
        if ($query->count() == 1)
        {
            $curr = $query->current();
                if($curr['active'] == 1){
                    $data['status'] = true;
                }else{
                    $data['telActive'] = $curr['telActive'];
                    $data['active'] = $curr['active'];
                    $data['status'] = false;

                }
            return $data;
//            var_dump($curr);
//            exit;
//            return $uid;
        }
        else
        {
            $data['status'] = 0;
            Passport::setCurrentUserUid(0);
            return $data;
        }
    }

    //发送短信
    public function action_send_msg(){
        $post = $this->request->post();
    	$phone = Arr::get($post,'phoneNum');
        $area = Arr::get($post,'area');
        $sms_obj = new Util_YunPianSms;
        $code = mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9).mt_rand(0,9);
        $data['mobile'] = $phone;
        $data['code'] = $code;
        $data['created'] = time();
        $id = $this->save($data);
        
        $tip = array('status'=>1,'msg'=>'fail');
        if($id>0){
        	if($area=="CN"){
            //中文模板
        	$tpl_id = 1330065;
        	$tpl_value = "#code#={$code}";
        	$rs=$sms_obj->send_sms_to_user_id($tpl_id, $tpl_value, $phone);
        	}else{
                //英文模板
        		$tpl_id = 1129805;
        		$tpl_value = "#code#={$code}";
        		$rs=$sms_obj->send_sms_to_user_id($tpl_id, $tpl_value, $phone);
        	}
            $rs = json_decode($rs,true);
            if($rs['code'] == 0){
                $tip = array('status'=>0,'msg'=>'success');
                echo json_encode($tip);
                exit;
            }
        	
        }
        echo json_encode($tip);
        exit;

    }

    public function save($data){
        list($insert_id, $rows) = DB::insert('user_v2_mobile_code')
            ->columns (array_keys($data))
            ->values (array_values($data))
            ->execute();
        return $insert_id;
    }

    public function action_mail(){
        $post = $this->request->post();
        $ret = array('status'=>0,'msg'=>'');
        $mail = Arr::get($post,'data');
        $query = DB::select()
            ->from('user_v2')
            ->where('userId','=',$mail)
            ->execute();
        if($query->count() > 0){
            $user = $query->current();
            $mail_data = User_Subscribe::user_activation($user['uid'],$mail,'confirm');
            $status = $mail_data['status'];
            if(!$status){
                $ret['status'] = 1;
                $ret['errormsg'] = "系统错误，稍后再试";
                $msg = "系统错误，稍后再试";
            }else{
                $ret['status']   = 0;
                $ret['msg']   = '发送成功';
                $msg = '发送成功';
            }
        }else{
            $ret['status'] = 1;
            $ret['msg'] = '用户不存在';
            $msg = '用户不存在';
        }
        echo $msg;
        exit;
    }
}
